package cn.git.javassist.learn;

import cn.git.javassist.util.BitStrUtil;
import javassist.*;

/**
 * @description:
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-15 02:14:18
 */
public class Monitor {
    public static void main(String[] args) throws NotFoundException, CannotCompileException {
        ClassPool pool = new ClassPool(true);
        String className = "cn.git.javassist.util.BitStrUtil";
        CtClass targetClass = pool.get(className);
        CtMethod method = targetClass.getDeclaredMethod("addString");
        CtMethod copyMethod = CtNewMethod.copy(method, method.getName().concat("$agent"), targetClass, null);
        targetClass.addMethod(copyMethod);

        String src = "{" +
                "long beginTime = System.nanoTime();" +
                "Object result = " + method.getName().concat("$agent($$);") +
                "long endTime = System.nanoTime();" +
                "System.out.println(endTime - beginTime);" +
                "System.out.println(endTime - beginTime);" +
                "return ($r)result; " +
                "}";
        method.setBody(src);

        // 将类加入至当前线程的 Thread.currentThread() getContextClassLoader()中
        targetClass.toClass();
        BitStrUtil bitStrUtil = new BitStrUtil();
        String s = bitStrUtil.addString(50);
        System.out.println(s);
    }
}
